package com.ple.app.importdata;

import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.ple.app.jzsf.R;
import com.ple.app.sevlet.DbOption;
import com.ple.app.sevlet.GetFromServer;
import com.ple.app.sevlet.GetIdList;
import com.ple.app.sevlet.JsonTools;
import com.ple.app.sevlet.NetConnect;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;



public class Inputcultivate_Activity extends Activity {

    private ListView listView;
    private TextView block_add;


   private LayoutInflater a;
    private int operation_id=0;//删除修改的ID

    private  final String[] culitivate_conlm={"ID","crop","seed","date","manure_number"};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_inputcultivate_);
        findbyid();
        inidata();
        updatalistview();
    }//oncreat

    /**
     * chong xin hui fu shi
     */
    @Override
    protected void onRestart() {
        super.onRestart();
        updatalistview();
    }

    /**
     * 绑定控件
     */
    private void findbyid(){
        listView= (ListView) findViewById(R.id.cultivate_listview);
        block_add= (TextView) findViewById(R.id.block_add);

    }
    /**
     * 初始化
     */
    private void inidata(){

        /**
         * 添加信息
         */
        block_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(Inputcultivate_Activity.this,Cultivate_Activity.class);
                startActivity(intent);
            }
        });
        /**
         * 点击显示查看或删除
         */
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                HashMap<String,String> getmap= (HashMap<String, String>) listView.getItemAtPosition(position);
                String ID=getmap.get("ID");
                operation_id=Integer.valueOf(ID);
                showdeletPopupWindow(view);
                //Toast.makeText(getApplicationContext(),ID,Toast.LENGTH_LONG).show();
            }
        });
        if(NetConnect.isNetworkAvailable(Inputcultivate_Activity.this))update();

        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {

                return false;
            }
        });
    }
    /**
     * 更新list view
     */
    private void updatalistview(){
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        MyopenHelper myopenhelper=new MyopenHelper(Inputcultivate_Activity.this,"seed.db",null,1);
        SQLiteDatabase db=myopenhelper.getReadableDatabase();
        Cursor curor=db.query("cultivate",culitivate_conlm,null,null,null,null,null,null);
       while (curor.moveToNext()){
            Map<String, Object> item = new HashMap<String, Object>();
            String id=curor.getString(0);
            String crop=curor.getString(1);
            String seed=curor.getString(2);
           String data=curor.getString(3);
            String manure=curor.getString(4);
            item.put("ID", id);
            item.put("crop", crop);
            item.put("seed", seed);
            item.put("date",data);
            item.put("manure_number", manure);
            list.add(item);}
            curor.close();
            db.close();
        SimpleAdapter adapter = new SimpleAdapter(Inputcultivate_Activity.this, list, R.layout.cultitave_item,
                new String[]{"ID", "crop", "seed", "date","manure_number"},
                new int[]{R.id.cultitaID, R.id.crop_Name, R.id.seed_type, R.id.cultita_time,R.id.cultita_manure});
        listView.setAdapter(adapter);

    }


    /**
     * 删除信息
     * @param view
     */
    private void showdeletPopupWindow(View view){
        // 一个自定义的布局，作为显示的内容
        View contentView = LayoutInflater.from(this).inflate(
                R.layout.pop_sqlopreation, null);
        // 设置按钮的点击事件
        /**
         * 查看
         */
        TextView share= (TextView) contentView.findViewById(R.id.see_more);
        share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String args=String.valueOf(operation_id);
               // Log.i("input", args);
                Intent intent=new Intent(Inputcultivate_Activity.this,Cultivateinfo_Activity.class);
                Bundle bundle=new Bundle();
                bundle.putString("id",args);
               intent.putExtras(bundle);
                startActivity(intent);

            }
        });
        /**
         * delet
         */
        TextView delet= (TextView) contentView.findViewById(R.id.delet_information);
        delet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                new AlertDialog.Builder(Inputcultivate_Activity.this).setTitle("系统提示")
                        .setMessage("确认删除此条信息？")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                                String[] args=new String[]{String.valueOf(operation_id)};
                                MyopenHelper myopenhelper=new MyopenHelper(Inputcultivate_Activity.this,"seed.db",null,1);
                                SQLiteDatabase db=myopenhelper.getReadableDatabase();
                                db.delete("cultivate","ID=?",args);
                                db.delete("cul_date","ID=?",args);
                                DbOption.adddeleid(db,"cultivate",operation_id);//需要删除的数据id给服务端
                                DbOption.adddeleid(db,"cul_date",operation_id);//需要删除的数据id给服务端
                                db.close();
                                // seeddatatolistview();
                                updatalistview();
                                Toast.makeText(getApplicationContext(),"已删除",Toast.LENGTH_LONG).show();
                            }
                        }).setNegativeButton("取消",null).create().show();
            }
        });
        /**
         * popwidow
         */
        final PopupWindow popupWindow = new PopupWindow(contentView, WindowManager.LayoutParams.WRAP_CONTENT
                , WindowManager.LayoutParams.WRAP_CONTENT , true);
        popupWindow.setTouchable(true);
        // 如果不设置PopupWindow的背景，无论是点击外部区域还是Back键都无法dismiss弹框
        // 我觉得这里是API的一个bug
        popupWindow.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                return false;
            }
        });
        // 设置好参数之后再show
        popupWindow.setBackgroundDrawable(getResources().getDrawable(
                R.drawable.bt_delet));
        // popupWindow.showAtLocation(view, Gravity.RIGHT,0,0);
        popupWindow.showAsDropDown(view,300,-175);
    }

    /**
     * 从服务端获得数据
     */
    private void update(){
        final Handler myHandler=new Handler() {
            @Override
            public void handleMessage(Message msg) {
                List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
                List<Map<String, Object>> list_c = new ArrayList<Map<String, Object>>();
                String rponse= (String) msg.obj;

                if(rponse.isEmpty()){
                    //Toast.makeText(getApplicationContext(),"网络连接异常",Toast.LENGTH_LONG).show();
                }
                else if(rponse.equals("1")){
                    //Toast.makeText(getApplicationContext(),"同步完成",Toast.LENGTH_LONG).show();
                }
                else{
                    list= JsonTools.getListmap("data",rponse);//获得服务器传来的数据
                    int size=list.size();
                    MyopenHelper myopenhelper = new MyopenHelper(Inputcultivate_Activity.this, "seed.db", null, 1);
                    SQLiteDatabase db = myopenhelper.getReadableDatabase();
                   // Log.i("input", "同步");
                    for(int i=0;i<size;i++){
                        Map<String, Object> item = new HashMap<String, Object>();
                        item= list.get(i);
                        String id= String.valueOf(item.get("id"));
                        String crop= String.valueOf(item.get("crop"));
                        String seed= String.valueOf(item.get("seed"));
                        String date= String.valueOf(item.get("date"));
                        String total= String.valueOf(item.get("total"));
                        String distance= String.valueOf(item.get("distance"));
                        String deep= String.valueOf(item.get("deep"));
                        String yield= String.valueOf(item.get("yield"));
                        String how_irr= String.valueOf(item.get("how_irr"));
                        String irr_number= String.valueOf(item.get("irr_number"));
                        String manure_number= String.valueOf(item.get("manure_number"));
                        /**
                         * 同步到本地
                         */
                        ContentValues values = new ContentValues();
                        values.put("ID", id);
                        values.put("crop", crop);
                        values.put("seed", seed);
                        values.put("date", date);
                        values.put("total", total);
                        values.put("distance", distance);
                        values.put("deep",deep);
                        values.put("yield", yield);
                        values.put("how_irr", how_irr);
                        values.put("irr_number", irr_number);
                        values.put("manure_number", manure_number);
                        db.insert("cultivate", null, values);
                    }// while(iterator.hasNext())
                    db.close();
                    SQLiteDatabase db1 = myopenhelper.getReadableDatabase();
                    list_c= JsonTools.getListmap("cul_data",rponse);//获得服务器传来的数据
                   // Log.i("input_list_c.size()", rponse);
                    //Log.i("input_list_c.size()", String.valueOf(list_c.get(1)));
                    for(int i=0;i<list_c.size();i++){
                        Map<String, Object> item = new HashMap<String, Object>();
                        item= list_c.get(i);
                        String id= String.valueOf(item.get("id"));
                        String operation= String.valueOf(item.get("operation"));
                        String date= String.valueOf(item.get("date"));

                        /**
                         * 同步到本地
                         */
                        ContentValues values = new ContentValues();
                        values.put("ID", id);
                        values.put("operation", operation);
                        values.put("date", date);
                        db1.insert("cul_date", null, values);
                    }
                    db1.close();
                   // Log.i("input", "updata");
                    updatalistview();
                    final String jsonstring= GetIdList.DBofcultivateToServer(Inputcultivate_Activity.this,rponse);

                    if(jsonstring.equals("0")){}
                    else{
                        //Log.i("input", "第2次线程");
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                GetFromServer getfromserver=new GetFromServer();
                                getfromserver.postDB(jsonstring,getfromserver.cultivate_url);
                            }
                        }).start();}

                }//else

            }
        };
        new Thread(new Runnable() {
            @Override
            public void run() {
                String jsonstring=GetIdList.getAllidFromTB(Inputcultivate_Activity.this,"cultivate");
                GetFromServer getfromserver=new GetFromServer();
                String result=getfromserver.dopost(jsonstring,null,getfromserver.cultivate_url);
                Message msg=new Message();
                msg.obj=result;
                myHandler.sendMessage(msg);
            }
        }).start();
    }
}

